# -*- coding: UTF-8 -*-
"""
Created on 2017-11-3

@author: F1231392
"""
import logging
import win32gui
from datetime import datetime, timedelta
# from pywinauto.SendKeysCtypes import SendKeys
from time import sleep

import win32com.client as win32
from pywinauto import application
from pywinauto.keyboard import SendKeys

titles = set()


class SuperNotes():
    def __init__(self, mail_path, username, password):

        self.login(mail_path, username, password)

    def lwfoo2(self, hwnd, mouse):
        # 去掉下面这句就所有都输出了，但是我不需要那么多
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            titles.add(win32gui.GetWindowText(hwnd))

    def login(self, mail_path, username, password):
        # print('backend:', application.Application().backend.name)  # win32
        self.app = application.Application(backend="win32").start (cmd_line=mail_path)
        #     app.Notepad.MenuSelect(u'文件->新建')

        sleep(20)
        #         win32gui.EnumWindows(self.lwfoo2, 0)
        #         lt = [t for t in titles if t]
        #         lt.sort()
        #         for t in lt:
        # #             print unicode(t,'big5'),66666
        #             logging.info(unicode(t,'big5'))
        hwnd = win32gui.FindWindow(None, "Welcome")
        # print('logging:', str(hwnd))
        logging.info(str(hwnd))
        win32gui.EnableWindow(hwnd, True)
        sleep(2)

        #         SendKeys('{ENTER}')
        #         sleep(2)
        #         SendKeys('{ENTER}')
        try:
            win32gui.SetForegroundWindow(hwnd)
        except:
            logging.info('NO NO NO NO')

        top_dlg = self.app.top_window()
        # top_dlg[u'立即使用'].click()

        sleep(2)
        top_dlg = self.app.top_window()
        sleep(2)
        top_dlg["Edit1"].type_keys(username)
        top_dlg["Edit2"].type_keys(password)
        sleep(2)
        #         print top_dlg.print_control_identifiers()
        logging.info('login.........')
        #         sleep(100)
        top_dlg[u'確定'].click()
        sleep(100)  # 100
        SendKeys("{ENTER}")
        sleep(60)  # 60

    def send_notes(self, message={}, fail_n=0, count_list=[]):
        """
        @note: message_dic requisite keys 'To','Cc','Title','Content'
        :return:
        """

        if 'To' in message.keys():
            SendKeys("^M")
            sleep(5)
            top_dlg = self.app.top_window()
            #             print top_dlg.print_control_identifiers()
            top_dlg["Edit4"].type_keys(message['To'])
            if 'Cc' in message.keys():
                top_dlg["Edit3"].type_keys(
                    message['Cc'])  # 'jay.zx.chuang@mail.foxconn.com,bear.x.jiang@mail.foxconn.com'
            top_dlg["Edit0"].type_keys(message['Title'])
            SendKeys("{TAB}")
            SendKeys("{TAB}")
            self.writeContent(message['Content'], top_dlg, fail_n, count_list)
            top_dlg['Button5'].click()
            top_dlg['Button10'].click()
            #             print top_dlg.print_control_identifiers()
            if 'Doc' in message.keys():
                self.add_doc(message['Doc'])
            SendKeys('%A')
            sleep(2)
            SendKeys('{ENTER}')
            sleep(60)

    def writeContent(self, content, top_dlg, fail_n, count_list):
        head = content[0].split(' ')
        for h in head:
            SendKeys(h)
            if h != head[-1]:
                SendKeys('{ }')
        SendKeys('{ENTER}')
        SendKeys('{ENTER}')
        SendKeys('{TAB}')

        SendKeys('{ENTER}')
        SendKeys('{ENTER}')

        SendKeys(content[2])

        #         SendKeys('{ENTER}')
        #         SendKeys('{UP}')
        SendKeys('{UP}')
        SendKeys('{UP}')
        today = datetime.now()
        dayOfweek = today.weekday()
        if dayOfweek != 0:
            day_a = (datetime.now() - timedelta(days=1)).strftime('%Y/%m/%d')
        else:
            day_a = (datetime.now() - timedelta(days=2)).strftime('%Y/%m/%d')
        SendKeys(day_a+'  ' + content[1] +u',詳細資訊請參考:http://10.175.94.58:8085')
        SendKeys('{ENTER}')
        # if fail_n > 1:
        #     SendKeys(day_a + u' AIRS系統辨識機台天線空隙處有雜質如下表,詳細資訊請參考:http://10.175.94.58:8086')
        #     SendKeys('{ENTER}')
        #     self.writeCount(count_list)
        #     self.insertImg(content[1], top_dlg, fail_n)
        # else:
        #     SendKeys(day_a + u' AIRS系統AI辨識結果報告如附件,詳細資訊請參考:http://10.175.94.58:8086')
        #     SendKeys('{ENTER}')
        #     self.writeCount(count_list)

    #         sleep(60)

    def writeCount(self, count_list):
        SendKeys("{TAB}")
        SendKeys(u'總辨識張數：')
        SendKeys(str(count_list[0]))
        SendKeys("{TAB}")
        SendKeys(u'系統辨識結果Pass：')
        SendKeys(str(count_list[1]))
        SendKeys("{TAB}")
        SendKeys(u'Fail：')
        SendKeys(str(count_list[2]))
        SendKeys('{ENTER}')

    def getFailimg(self, file_path, fail_n):
        excel = win32.Dispatch('Excel.Application')
        logging.info(file_path)
        wb = excel.Workbooks.open(file_path)
        ws = wb.Worksheets('AIRS')
        len_num = fail_n / 400
        for n_row in range(len_num + 1):
            if n_row == len_num:
                range_str = 'A%d:N%d' % (400 * n_row + 1, fail_n)
            else:
                range_str = 'A%d:N%d' % (400 * n_row + 1, 400 * n_row + 400)
            ws.Range(range_str).CopyPicture()
            ws.Paste(ws.Range('P%d' % (400 * n_row + 1)))
            ws.Shapes('Picture %d' % (n_row + 1)).copy()

            sleep(1)
            SendKeys("^V")
            sleep(10)
            SendKeys('{ENTER}')
            if (n_row + 1) * 400 == fail_n:
                break
        return wb

    def insertImg(self, img_path, top_dlg, fail_n):

        #         top_dlg['ComboBox2'].TypeKeys('12')
        #         for x in range(15):
        #             SendKeys('{TAB}')
        #             sleep(0.5)
        wb = self.getFailimg(img_path, fail_n)

        wb.Save()
        sleep(15)
        try:
            wb.close()
        except:
            pass

        sleep(1)

    def add_doc(self, file_list):
        for filepath in file_list:
            SendKeys('%A')
            sleep(2)
            SendKeys('{DOWN}')
            SendKeys('{DOWN}')
            SendKeys('{DOWN}')
            SendKeys('{DOWN}')
            SendKeys('{ENTER}')
            #         top_dlg = self.app.top_window_()
            sleep(2)
            SendKeys(filepath)
            SendKeys('{ENTER}')
            sleep(2)

    def close(self):
        SendKeys("%F")
        sleep(1)
        SendKeys('{UP}')
        sleep(1)
        SendKeys('{ENTER}')
        sleep(1)
        SendKeys('{ENTER}')


# if __name__ == '__main__':

    # S_N = SuperNotes(r'C:\Program Files (x86)\Super Notes\SuperNotes.exe', 'luke.xf.zhang@mail.foxconn.com', 'Asdf*963.')
    # message_dic = {}
    # message_dic['To'] = 'luke.xf.zhang@mail.foxconn.com'
    # #     message_dic['Cc'] = 'hardy.w.liu@mail.foxconn.com'
    # message_dic['Title'] = u'Super Notes 自動化'
    # message_dic['Content'] = ['Dear All:', r'C:\Users\F1233225\Desktop\败犬N连.png',
    #                           u'luke  /luke.xf.zhang@mail.foxconn.com/EERF-FATP SW/EXT.GL : 77875']
    # # message_dic['Doc'] = [r'C:\Users\F1231392\Desktop\20171103.docx']
    # S_N.send_notes(message_dic, 6)
    # S_N.close()
